﻿using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Smile.Mvvm.Service
{
    /// <summary>Service which manage operations with the application settings storage.</summary>
    public class SettingsService : ISettingsService
    {
        // @Indexer
        public object this[string key]
        {
            get
            {
                return _appSettings[key];
            }
            set
            {
                lock (_locker)
                {
                    _appSettings[key] = value;
                    _appSettings.Save();
                }
            }
        }


        // @Public
        public void Add(string key, object value)
        {
            if (_appSettings.Contains(key))
            {
                _appSettings[key] = value;
            }
            else
            {
                lock (_locker)
                {
                    _appSettings.Add(key, value);
                    _appSettings.Save();
                }
            }
            
        }

        public bool Contains(string key)
        {
            return _appSettings.Contains(key);
        }

        public void Remove(string key)
        {
            lock (_locker)
            _appSettings.Remove(key);
            _appSettings.Save();
        }

        public bool TryGetValue<T>(string key, out T value)
        {
            return _appSettings.TryGetValue<T>(key, out value);
        }


        // @Private
        IsolatedStorageSettings _appSettings = IsolatedStorageSettings.ApplicationSettings;
        object                  _locker = new object();
    }
}
